import store from '@/store'
import { defineStore } from 'pinia'
import { RouteRecordRaw } from 'vue-router'
// import { constantRoutes, asyncRoutes } from '@/router'
// const modules = import.meta.glob('@/views/**/**.vue')
// console.log(modules, '1111')
import { constantRoutes } from '@/router'

import { getRouterList } from '@/api/router'

interface IPermissionState {
  routes: RouteRecordRaw[]
  dynamicRoutes: RouteRecordRaw[]
}

const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => {
      if (route.meta?.roles !== undefined) {
        return route.meta.roles.includes(role)
      } else {
        return false
      }
    })
  } else {
    return true
  }
}

const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const res: RouteRecordRaw[] = []
  routes.forEach((route) => {
    const r = { ...route }
    if (hasPermission(roles, r)) {
      if (r.children) {
        r.children = filterAsyncRoutes(r.children, roles)
      }
      res.push(r)
    }
  })
  return res
}

export const usePermissionStore = defineStore({
  id: 'permission',
  state: (): IPermissionState => {
    return {
      routes: [],
      dynamicRoutes: []
    }
  },
  actions: {
    async setRoutes(roles: string[]) {
      // const res = await getRouterList()
      // let asyncRoutes1 = []
      // if (res.errcode === 0) {
      //   asyncRoutes1 = res.data.rows.map((el) => {
      //     return {
      //       path: el.path,
      //       component: modules[`@/views/${el.path}/index.vue`],
      //       name: el.menuName,
      //       meta: {
      //         title: el.menuName,
      //         icon: 'lock',
      //         roles: ['admin']
      //         // alwaysShow: true // 将始终显示根菜单
      //       }
      //     }
      //   })
      // }
      // let accessedRoutes
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes
      //   // accessedRoutes = asyncRoutes1
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      //   // accessedRoutes = filterAsyncRoutes(asyncRoutes1, roles)
      // }
      // console.log(accessedRoutes, 'accessedRoutes')
      // this.routes = constantRoutes.concat(accessedRoutes)
      // this.dynamicRoutes = accessedRoutes

      this.routes = constantRoutes
      this.dynamicRoutes = constantRoutes
    }
  }
})

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
